package com.ccys.cms.controller.inventory;


import cn.hutool.core.util.IdUtil;
import com.ccys.cms.service.inventory.ExchangeOrderDetailService;
import com.ccys.cms.service.inventory.ExchangeOrderService;
import com.ccys.cms.service.inventory.InventoryFeedService;
import com.ccys.cms.service.inventory.PurchaseOrderDetailService;
import com.ccys.cms.service.productAndService.ProductService;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.web.inventory.ExchangeOrderDto;
import com.ccys.db.dto.web.inventory.ExchangeOrderPageDto;
import com.ccys.db.entity.*;
import com.ccys.db.mapper.TblPurchaseOrderMapper;
import com.ccys.db.vo.web.inventory.ExchangeOrderDetailVo;
import com.ccys.db.vo.web.inventory.ExchangeOrderVo;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/inventory")
@Api(tags = "退换货")
public class ExchangeOrderController {


    @Resource
    private ExchangeOrderService service;

    @Resource
    private PurchaseOrderDetailService purchaseService;

    @Resource
    private ExchangeOrderDetailService exchangeOrderDetailService;

    @Resource
    private ProductService productService;

    @Resource
    private PurchaseOrderDetailService orderDetailService;

    @Resource
    private InventoryFeedService feedService;

    @Resource
    private TblPurchaseOrderMapper purchaseOrderMapper;

    @ApiOperation("新增")
    @PostMapping("exchangeOrder")
    @Transactional
    public ResponseResult save(@RequestBody ExchangeOrderDto dto) {

        long createdOnUtc = new Date().getTime();
        TblPurchaseOrder order = dto.getOrder();
        List<TblPurchaseOrderDetail> purchaseList = dto.getPurchaseList();
        List<TblPurchaseExchangeOrderDetail> exchangeList = dto.getExchangeList();
        //采购单类型 Purchase:采购单;Exchange:退换货单
        order.setType("Exchange");
        //生成重新采购的订单编号
        //生成code
        String code = IdUtil.getSnowflakeNextId() + "";
        order.setCode(code);
        int num = service.insertOrUpdate(order);
        //生成detail编号
        //生成规则:根据顺序，在采购单的 code 后面添加 3 为数字，例如:xxxxx001,xxxxx002
        for (int i = 0; i < purchaseList.size(); i++) {
            String formattedNumber = String.format("%03d", i);
            String detailCode = code + formattedNumber;
            TblPurchaseOrderDetail detail = purchaseList.get(i);
            detail.setCode(detailCode);
            //生成id
            detail.setId(IdUtil.getSnowflakeNextIdStr());
            //设置orderId
            detail.setOrderId(order.getId());
            detail.setCreatedOnUtc(createdOnUtc);
        }
        //批量添加Purchasedetail
        purchaseService.insertAll(purchaseList);
        //批量添加ExchangeDetail
        exchangeList.forEach(x->{
            x.setId(IdUtil.getSnowflakeNextIdStr());
            x.setOrderId(order.getId());
            x.setCreatedOnUtc(createdOnUtc);
        });
        exchangeOrderDetailService.insertAll(exchangeList);
        // 库存的修改: 修改总库存 = 原先的库存减去退货的(注意一定不能减多了)
        // 没激活的批次就不用管了
        String codeListStr = exchangeList.stream().map(x -> x.getOrderDetailCode()).collect(Collectors.joining(","));
        // 1、查询productId
        List<TblPurchaseOrderDetail> detailList = orderDetailService.findListByLimit(TblPurchaseOrderDetail.class, new ArrayList<String>() {{
            add(" del_flag = 0 ");
            add(" code in (" + codeListStr + ") ");
        }}, "created_on_utc desc");

        List<TblProduct> productList = new ArrayList<>();
        List<TblInventoryFeed> feedList = new ArrayList<>();
        for (int j = 0; j < detailList.size(); j++) {
            TblPurchaseOrderDetail detail = detailList.get(j);
            String productId = detail.getProductId();
            Integer quantity = exchangeList.get(j).getQuantity();
            //要激活的才会修改库存，否则待会修改库存会出现负数
            //add(" status = 1 ");
            if(1==detail.getStatus()){
                TblProduct product = new TblProduct();
                product.setId(productId);
                product.setQtyImportInStock(quantity);
                productList.add(product);
            }
            //添加库存流水记录
            TblInventoryFeed feed = new TblInventoryFeed();
            feed.setProductId(productId);
            feed.setQuantity(quantity);
            BigDecimal priceUnit = detail.getPriceUnit();
            feed.setCostPricePerUnit(priceUnit);
            //null 进货 2 -> paid,4 -> manual adjustment, 5 -> write_off(废弃) ,6 -> staff purchase,7 -> 退换货中的退货(2.0新增)
            feed.setType(7);
            feed.setPurchaseOrderId(detail.getOrderId());
            feed.setPurchaseOrderDetailId(detail.getId());
            feed.setId(IdUtil.getSnowflakeNextIdStr());
            feed.setCreatedOnUtc(createdOnUtc);
            feedList.add(feed);
        }
        if(CollectionUtils.isNotEmpty(productList)){
            productService.updateBatchImportQuantity(productList);
        }
        if(CollectionUtils.isNotEmpty(feedList)){
            //添加库存流水记录
            feedService.insertAll(feedList);
        }
        return ResponseResult.update(num);
    }


    @ApiOperation("根据id查询")
    @GetMapping("exchangeOrder/detail")
    public ResponseResult<ExchangeOrderDetailVo, Object> getbyId(String id) {
        ExchangeOrderDetailVo res = purchaseOrderMapper.getExchangeOrderDetail(id);
        return ResponseResult.success(res);
    }



    @ApiOperation(value = "查询分页",notes = "排序字段 t1.code(指的是 exchangeOrderNo列) /t2. user_fullname / t1.created_on ")
    @GetMapping("exchangeOrder")
    public ResponseResult<PageInfo<ExchangeOrderVo>,Object> getPage(ExchangeOrderPageDto dto){
        return service.getPage(dto);
    }

}
